package com.mms.action;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;

import com.mms.dao.InvitationDao;
import com.mms.entity.InvitationMessage;
import com.opensymphony.xwork2.Action;

public class MessageAction implements Action {

    
    public String getNewMessageCount() throws Exception{
        HttpServletRequest request=ServletActionContext.getRequest();
        request.setCharacterEncoding("UTF-8");
        InvitationDao invitationDao=new InvitationDao();
        int newMessageCount=invitationDao.getNewInvitationMessageCountByStaffID(Integer.parseInt(request.getSession().getAttribute("userID").toString()));
        JSONArray jsonArray = JSONArray.fromObject(newMessageCount); 
        HttpServletResponse response=ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        System.out.println(jsonArray.toString());
        out.print(jsonArray.toString());
        out.flush();
        out.close();
        return SUCCESS;
    }
    
    public String getInvitationInfo() throws UnsupportedEncodingException {
        HttpServletRequest request=ServletActionContext.getRequest();
        request.setCharacterEncoding("UTF-8");
        InvitationDao invitationDao=new InvitationDao();
        List<InvitationMessage> messages=invitationDao.getInvitationByStaffID(Integer.parseInt(request.getSession().getAttribute("userID").toString()));
        for (InvitationMessage message : messages) {
            invitationDao.setInvitationRead(message.getTopic(), Integer.parseInt(request.getSession().getAttribute("userID").toString()));
        }
        request.setAttribute("message", messages);
        System.out.println(messages.toString());
        return SUCCESS;
    }
    
    
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}
